<template>
  <div>
    <el-upload
      :disabled="disabled"
      :show-file-list="showFileList"
      :file-list="internalFileList"
      :limit="1"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-preview="handlePreview"
      :http-request="doUpload"
      list-type="picture"
      accept="image/png,image/jpeg"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="internalFileList[0] && internalFileList[0].url" alt="" />
      <!-- <div v-if="internalFileList[0] && internalFileList[0].name" style="margin-top:8px;color:#606266;word-break:break-all;">{{ internalFileList[0].name }}</div> -->
    </el-dialog>
  </div>
  
</template>

<script>
import { policy as uploadImage } from '@/api/oss/policy'

export default {
  name: 'singleUpload',
  props: {
    value: String,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined
      },
      set: function () {}
    }
  },
  data() {
    return {
      dialogVisible: false,
      internalFileList: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          const name = newVal.substr(newVal.lastIndexOf('/') + 1)
          this.internalFileList = [{ name, url: newVal }]
        } else {
          this.internalFileList = []
        }
      }
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove() {
      this.emitInput('')
    },
    handlePreview() {
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('仅支持 JPG/PNG 格式')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('图片大小不能超过 10MB')
        return false
      }
      return true
    },
    async doUpload(request) {
      try {
        const formData = new FormData()
        formData.append('image', request.file)
        const resp = await uploadImage(formData)
        // 兼容两种返回：{ code, data:url } 或 { code, msg:url }
        const url = resp.data || resp.msg
        this.internalFileList = [{ name: request.file.name, url }]
        this.emitInput(url)
        request.onSuccess && request.onSuccess({}, request.file)
      } catch (e) {
        this.$message.error(e?.message || '上传失败，请重试')
        request.onError && request.onError(e)
      }
    }
  }
}
</script>

<style>
</style>


